<?php

namespace app\index\controller;

use think\Db as orgCreatorDB;
use think\Log;
use think\Cache;


class OrgCreator extends Common{

    public $datas;

    /**
     * 刷新 合作作者，机构表
     */
    public function updateOrgCreator(){
        /**
         * userId              名片编号
         */
        $this->datas = $this->params;

        $this->updateOrgCreatorService($this->datas['userId']);

        $this->returnMsg(1, '操作成功！');
    }


    private function updateOrgCreatorService($userId){

        //查询学者id
        $user = orgCreatorDB::table('user')->where('id',$userId)->find();

        //查询名片关联资源信息
        $sql = "SELECT l.creatorStandard,l.instituteStandard FROM user_resource u  LEFT JOIN local_resource_collection l on l.id = u.resource_id WHERE u.user_id = ".$userId." and l.id is not null";
        $res = orgCreatorDB::query($sql);

        $insertOrgArr = array(); 
        $insertCreatorArr=array(); 
        if(!empty($res)){
            $orgArr=array(); 
            $creatorArr=array(); 
            foreach($res as $resource){
                if(!empty($resource['creatorStandard'])){
                    $creatorStandardArr = json_decode($resource['creatorStandard'], true);
                    $creatorArr = array_merge($creatorArr,$creatorStandardArr);
                }
                if(!empty($resource['instituteStandard'])){
                    $instituteStandardArr = json_decode($resource['instituteStandard'], true);
                    $orgArr = array_merge($orgArr,$instituteStandardArr);
                }
            }

            $creator = array_count_values($creatorArr);
            $org = array_count_values($orgArr);

            foreach ($creator as $key => $value) {
                $oneCreator = [];
                $oneCreator["name"] = $key;
                $oneCreator["count"] = $value;
                $insertCreatorArr[] = $oneCreator;
                
            }


            foreach ($org as $key => $value) {
                $oneOrg = [];
                $oneOrg["name"] = $key;
                $oneOrg["count"] = $value;
                $insertOrgArr[] = $oneOrg;
                
            }
        }
        $delsql = "DELETE FROM  user_org_creator where scholar_id = ".$user["scholar_id"];
        orgCreatorDB::execute($delsql);
        if(!empty($insertCreatorArr) || !empty($insertOrgArr)){
            $insertData = [];
            $insertData['scholar_id'] = $user["scholar_id"];
            $insertData['org_name'] = json_encode($insertOrgArr,JSON_UNESCAPED_UNICODE);
            $insertData['creator'] = json_encode($insertCreatorArr,JSON_UNESCAPED_UNICODE);

            orgCreatorDB::table('user_org_creator')->insert($insertData);

        }


    }



}